package com.supostacks.xuetanginterfaces.facade;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.supostacks.application.application.IBaseApplication;
import com.supostacks.rpc.server.IDataDeployService;
import com.supostacks.rpc.server.req.DeployReq;
import com.supostacks.rpc.server.res.XResult;
import com.supostacks.xuetanginterfaces.factory.DefaultFactory;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.util.StringUtils;

import java.util.Date;

@DubboService
public class DataDeployImpl implements IDataDeployService {
    @Override
    public XResult deploy(DeployReq req) {
        XResult res = new XResult(200, "success");
        try {
            JSONObject data = (JSONObject) JSON.toJSON(req.getData());
            IBaseApplication baseApplication = DefaultFactory.getApplication(req);
            assert baseApplication != null;
            String type = req.getType();

            String id;
            switch (type) {
                case "insert":
                    String dataId = data.getString("id");
                    if (!StringUtils.hasText(dataId)) {
                        data.put("id", IdUtil.nanoId());
                    }
                    data.put("createTime", new Date());
                    id = baseApplication.insert(data);
                    if(StringUtils.hasText(id))
                        res.setResult(data);
                    break;

                case "update":
                    id = baseApplication.updateById(data);
                    if(StringUtils.hasText(id))
                        res.setResult(data);
                    break;

                case "delete":
                    baseApplication.deleteById(req.getId());
                    break;

            }
        } catch (Exception e) {
            res.setCode(500);
            res.setMsg(e.getMessage());
        }
        return res;
    }

}
